from PIL import Image
import pyocr
import sys
import matplotlib.pyplot as plt
import cv2 as cv
import pytesser3
#- - -
import sys, urllib, json
import base64

#数字识别

#数字识别 - - - 提取数字
mWidth = 550
mHeight = 165
#方向
turnX = [-1,0,1]
turnY = [-1,0,1]
#删除外边框 - BFS
def DropRect(img,x,y,isFind):
    if isFind:
        listImg = []
        listImg.append((x,y))
        while(len(listImg) != 0):
            x,y = listImg[0]
            del listImg[0]
            # print(x,y)
            img[x,y] = 255
            for i in range(3):
                for j in range(3):
                    ti = x + turnX[i]
                    tj = y + turnY[j]
                    if ti < 0 or tj < 0 or ti >= img.shape[0] or tj >= img.shape[1] or img[ti,tj] == 255:
                        continue
                    img[ti, tj] = 255
                    listImg.append((ti,tj))
    else:
        for i in range(img.shape[0]):
            for j in range(img.shape[1]):
                #找到第一个黑点，然后删除该连通域
                if img[i,j] == 0:
                    # print(str(i) + "  " + str(j))
                    img[i,j] = 255
                    DropRect(img,i,j,True)
                    return

#数字区域选择
def Diget():
    image = cv.imread("./img/digetOcr.jpg")
    #存一个原始图
    orginImage = image
    #灰度图
    image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    #二值图
    # image = cv.adaptiveThreshold(image, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 11, 2)
    #试卷号
    imageTop1 = image[145:310,150:700]
    orginTop1 = orginImage[145:310,150:700]

    #均值滤波+固定阈值 过滤小面积干扰
    meanImg1 = cv.blur(imageTop1, (3, 3))
    meanImg1 = cv.threshold(meanImg1, 50, 255, cv.THRESH_BINARY)[1]

    #身份证号
    # imageTop2 = image[330:480,150:1700]
    #存入图片
    # cv.imwrite("./img/imageTop1.jpg",imageTop1)
    # cv.imwrite("./img/imageTop2.jpg",imageTop2)
    #重新调整大小
    meanImg1 = cv.resize(imageTop1, (mWidth, mHeight), cv.INTER_LANCZOS4)
    #删除边界框
    DropRect(meanImg1,0,0,False)
    # 绘图查看坐标长宽
    # plt.figure()
    # plt.subplot(131)
    # plt.imshow(imageTop1,cmap='gray')
    # plt.show()
    # meanImg = cv.blur(imageTop1, (3, 3))

    # contours = cv.findContours(meanImg1, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)[1]
    # print(len(contours))
    # for contour in contours:
    #     cRect = cv.minAreaRect(contour)
    #     cX = int(cRect[0][0])
    #     cY = int(cRect[0][1])
    #     area = cX * cY
    #     print(area)
    #     if area < 10000:
    #         cv.circle(orginTop1, (cX, cY), 2, (0, 0, 255), -1)

    #将最终只有数字的图片存入文件
    cv.imwrite("./img/digetOcr1.jpg",meanImg1)

    cv.namedWindow("OrginImage",0)
    cv.imshow("OrginImage",orginTop1)
    cv.namedWindow("ImageTop1",0)
    cv.imshow("ImageTop1",meanImg1)
    cv.waitKey(0)

#识别数字-API
def digetOcr():
    url = 'http://apis.baidu.com/idl_baidu/baiduocrpay/idlocrpaid'

    data = {}
    data['fromdevice'] = "pc"
    data['clientip'] = "10.10.10.0"
    data['detecttype'] = "LocateRecognize"
    data['languagetype'] = "ENG"
    data['imagetype'] = "1"

    file_object = open('./img/digetOcr1.jpg','rb')
    try:
         tmp = file_object.read( )
    finally:
         file_object.close( )
    data['image'] = base64.b64encode(tmp)

    decoded_data = urllib.parse.urlencode(data)
    decoded_data = decoded_data.encode('utf-8')

    req = urllib.request.Request(url, data = decoded_data)

    req.add_header("Content-Type", "application/x-www-form-urlencoded")
    req.add_header("apikey", "695bfba0d29a36648a604af03fcd1596")

    resp = urllib.request.urlopen(req)
    content = resp.read()
    # print(type(content))
    # print(content)
    contentDe = content.decode('ascii')
    if(content):
        con = json.loads(contentDe)['retData'][0]['word']
        for c in con:
            if c == ' ':
                continue
            if c == 'd' or c == 'D':
                print('0',end=' ')
                continue
            print(c,end=' ')
        print()

#数字图片预处理，膨胀
def imgPre():
    # 读入图片
    image = cv.imread("./img/digetOcr1.jpg")
    # 进行膨胀，便于识别
    image = cv.erode(image, None, iterations=3)
    # 存入图片
    cv.imwrite("./img/digetOcr1.jpg", image)
    # 显示
    cv.imshow("ImageTop1",image)
    cv.waitKey(2000)

#选择出数字
Diget()
#预处理膨胀，便于识别
imgPre()
#OCR数字识别 - - 第一种方法 百度API
digetOcr()

#OCR数字识别 - - 第二种方法  使用tesseract
# tools = pyocr.get_available_tools()[:]
# if len(tools) == 0:
#     print("no ocr tool found")
#     sys.exit(1)
# else:
#     print("Using '%s' " % tools[0].get_name())
#
# image = Image.open("./img/digetOcr1.jpg")
# # code = pytesseract.image_to_string((image))
# # print(code)
# print(tools[0].image_to_string(image))

#效果不佳
#print(pytesser3.image_file_to_string("./img/digetOcr1.jpg"))